<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in Hlist" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { grtList } from '@/api/employees'
import { addData, getDataout, putData } from '@/api/departments'
export default {
  name: 'VueWhZr3DeptDialog',

  props: {
    id: {
      required: true,
      type: String
    },
    isShow: {
      required: true,
      type: Boolean
    },
    reingList: {
      required: true,
      type: Array
    }
  },

  data() {
    // 校验部门编码是否重复
    const validCode = (rule, value, callback) => {
      console.log(value)
      console.log(this.reingList)
      let arr = this.reingList.map(item => item.code)
      if (this.isShow) {
        // 把当前正在编辑的部门编号（this.id）排除在外,过滤掉当前的部门, map得到部门编号列表
        arr = this.reingList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (arr.includes(value)) {
        callback(new Error(`编码:${value} 已存在`))
      } else {
        callback()
      }
    }
    // 校验部门名称
    const validName = (rule, value, callback) => {
      console.log()
      let existNameList = this.reingList.filter(item => item.id === this.id).map(item => item.name)
      if (this.isShow) {
        console.log(this.reingList)
        const dept = this.reingList.find(item => item.id === this.id)
        // console.log(dept)
        // 2. 取出pid(它的父级是谁)
        const pid = dept.pid
        // 3. 过滤： 同一个父级，不包括自己； map： 只要需要名字
        existNameList = this.reingList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
      }
      // console.log(isName)

      if (existNameList.includes(value)) {
        callback(new Error(`部门名称 ${value} 已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门管理者', trigger: ['change', 'blur'] }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      Hlist: []
    }
  },

  created() {
    this.lodeList()
    if (this.isShow) {
      this.lodeDataout()
    }
  },

  methods: {
    // 获取负责人信息
    async lodeList() {
      try {
        const res = await grtList()
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.Hlist = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取单个数据，来完成回显
    async lodeDataout() {
      try {
        const res = await getDataout(this.id)
        console.log(res)
        if (res.code === 10000) {
          this.form = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    //  表单校验
    hSubmit() {
      //  兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 校验失败
        // 判断是编辑还是新增
        this.isShow ? this.lodePutData() : this.lodeData()
      })
    },

    // 新增
    async lodeData() {
      try {
        const res = await addData({ ...this.form, pid: this.id })
        console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 使用子传父，通知父组件更新列表
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑
    async lodePutData() {
      try {
        const res = await putData(this.form)
        // console.log(res)
        if (res.code === 10000) {
          this.$message.success(res.message)
        }
        // 编辑完成后，通知父组件更新列表
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
